# -*- coding: utf-8 -*-
# article_info.py
# Created by Hardy on 26th, Jan
# Copyright 2017 杭州网川教育有限公司. All rights reserved.


from querier.esquerier import ElasticSearchQuerier
from neo4j.v1 import GraphDatabase

uri = "bolt://localhost:7687"
driver = GraphDatabase.driver(uri, auth=("neo4j", "whq"))


class StarRelationshipQuerier(ElasticSearchQuerier):

    def __init__(self, config):
        super(StarRelationshipQuerier, self).__init__(None, None, None)
        self.neo4j_url = config['neo4j_url']
        self.user = config['user']
        self.password = config['password']
        self.driver = GraphDatabase.driver(self.neo4j_url, auth=(self.user, self.password))

    def exec_cypher(self, cql, returns):
        records = []
        with self.driver.session() as session:
            with session.begin_transaction() as tx:
                for record in tx.run(cql):
                    records.append([record[k] for k in returns])
        return records

    def search(self, args):
        arg_dict = args.get('arg_dict')
        arg_dict = {} if not arg_dict else arg_dict

        star = arg_dict.get('star', '')
        movie = arg_dict.get('movie', '')
        drama = arg_dict.get('drama', '')
        res = []

        try:
            cql = """
            match (p :Person) -[r]- (q :Person) where p.name='%s' return p, r, q
            """ % (star, )
            res = self.exec_cypher(cql, ['p.name', 'r.desc', 'q.name'])

        except Exception as e:
            print(str(e))
        finally:
            pass

        result = []
        return {
            "result": result
        }

    def _build_query(self, args): pass

    def _build_result(self, result, param): pass
